import re
import os
import requests


# 登录git
def login_git(host, port, username, password):
    cookies = None
    try:
        form = {'wicket:bookmarkablePage': ':com.gitblit.wicket.pages.MyDashboardPage', 'id1_hf_0': '',
                'username': username, 'password': password}
        r = requests.post(
            f'https://{host}:{port}/?wicket:interface=:0:userPanel:loginForm::IFormSubmitListener::', data=form,
            verify=False, allow_redirects=False, timeout=5)
        if r.status_code == 302:
            JSESSIONID = None
            Gitblit = None
            cookies_info = r.headers['Set-Cookie']
            m = re.search(r'JSESSIONID=([\s\S]+?);', cookies_info)
            if m:
                JSESSIONID = m.group(1)
            m = re.search(r'Gitblit=([\s\S]+?);', cookies_info)
            if m:
                Gitblit = m.group(1)
            if JSESSIONID and Gitblit:
                cookies = {'JSESSIONID': JSESSIONID, 'Gitblit': Gitblit}
    except Exception as e:
        print('Gitblit login failed, ', e)
    return cookies


# 获取分支最新hash
def get_lastest_version(host, port, repository, branch, cookies):
    try:
        r = requests.get(f'https://{host}:{port}/log/{repository}.git/{branch}', verify=False, cookies=cookies)
        if r.status_code == 200:
            m = re.search(r'class="shortsha1" title="(.+?)"', r.text)
            if m:
                return m.group(1)
    except Exception as e:
        print('Get branch version failed. Reason:', e)
    return None


def download_branch_zip(host, port, repository, version, cookies, path):
    try:
        r = requests.get(f'https://{host}:{port}/zip/?r={repository}.git&h={version}&format=zip', verify=False,
                         cookies=cookies)
        if r.status_code == 200:
            os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
            with open(path, 'wb') as f:
                f.write(r.content)
        else:
            raise Exception('status code:' + str(r.status_code))
    except Exception as e:
        print('Download zip failed. Reason:', e)
